<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/1/29
 * Time: 16:27
 */

namespace app\api\service;

use app\api\controller\Fun;
use app\common\Service;
use think\Config;

class WxService extends Service
{
     private $appid = null;
     private $appsecret = null;

     public function __construct()
     {
//         $this->appid = Config::get('wx_dl.app_id');
//         $this->appsecret = Config::get('wx_dl.app_secret');
     }

    /**
     * 根据微信code值获取用户信息
     * @param $code
     * @return mixed|string
     */
    public function getInfoByCode($code, $type = 'dl',$encryptedData = '',$iv = '')
    {
        $this->appid = Config::get('wx_'.$type.'.app_id');
        $this->appsecret = Config::get('wx_'.$type.'.app_secret');

        //拼接url
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';

        //新版小程序登陆   todo
        if($type == 'miniprogram'){
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->appsecret.'&grant_type=authorization_code&js_code='.$code;
        }

        $res = file_get_contents($url);
        self::$data = json_decode($res,true);

        //判断是否成功
        if(empty(self::$data['errcode'])){
            if(empty(self::$data['unionid'])){
                $rtn = $this->getUnionId(self::$data['session_key'],$encryptedData,$iv);
                if(!$rtn){
                    self::$data['errmsg'] = '获取unionid失败';
                    return false;
                }
                self::$data['unionid'] = $rtn;
            }
            return true;
        }else{
            return false;
        }
    }

    /**
     * 未在公众平台下所有账号登陆过的账号需要单独获取unionid
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     * @return bool
     */
    public function getUnionId($sessionKey,$encryptedData,$iv)
    {
        Fun::LOG(json_encode([$sessionKey,$encryptedData,$iv]),'wx_miniprogram_login');

        include_once dirname(__FILE__) . '/../../../extend/aes/wxBizDataCrypt.php';

        $pc = new \WXBizDataCrypt($this->appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $data = json_decode($data);
            return $data->unionId;
        } else {
            return false;
        }
    }
}